<template>
  <div class="content-manage">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="标题">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="contentList" border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="title" label="标题" />
      <el-table-column label="图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="row.pic"
            :preview-src-list="[row.pic]"
            fit="cover"
            style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="url" label="链接" show-overflow-tooltip />
      <el-table-column prop="sortOrder" label="排序" width="80" />
      <el-table-column label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      @closed="handleDialogClosed"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="图片" prop="pic">
          <el-upload
            class="avatar-uploader"
            :action="`${import.meta.env.VITE_APP_BASE_API}/content/upload`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <img v-if="form.pic" :src="form.pic" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listContent, saveContent, updateContent, deleteContent } from '@/api/content'
import { getToken } from '@/utils/auth'

const loading = ref(false)
const contentList = ref([])
const total = ref(0)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: ''
})

const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

const formRef = ref()
const form = reactive({
  id: undefined,
  title: '',
  pic: '',
  url: '',
  sortOrder: 0,
  status: 1
})

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  pic: [{ required: true, message: '请上传图片', trigger: 'change' }],
  url: [{ required: true, message: '请输入链接', trigger: 'blur' }]
}

const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const res = await listContent(queryParams)
    contentList.value = res.data.records
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 新增
const handleAdd = () => {
  dialog.type = 'add'
  dialog.title = '新增广告'
  dialog.visible = true
  Object.assign(form, {
    id: undefined,
    title: '',
    pic: '',
    url: '',
    sortOrder: 0,
    status: 1
  })
}

// 编辑
const handleEdit = (row) => {
  dialog.type = 'edit'
  dialog.title = '编辑广告'
  dialog.visible = true
  Object.assign(form, row)
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该广告吗？', '提示', {
      type: 'warning'
    })
    await deleteContent(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    console.log('取消删除')
  }
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  form.pic = res.data
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    if (dialog.type === 'add') {
      await saveContent(form)
      ElMessage.success('新增成功')
    } else {
      await updateContent(form)
      ElMessage.success('修改成功')
    }
    dialog.visible = false
    getList()
  } catch (error) {
    console.log('表单校验失败')
  }
}

// 对话框关闭回调
const handleDialogClosed = () => {
  formRef.value?.resetFields()
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.content-manage {
  .search-form {
    margin-bottom: 20px;
  }
  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }
  
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style> 